<?php
/*
 * @Author: 李红雨 - RainLee <rainlee1990@yeah.net>
 * @Date: 2022-05-19 17:12:49
 * @LastEditors: 李红雨 - RainLee <rainlee1990@yeah.net>
 * @LastEditTime: 2022-05-22 16:56:25
 * @Description: 文件说明
 */

declare(strict_types=1);

namespace rainlee\route\dispatch;

use think\Response;
use think\route\RuleItem;

/**
 * Url Dispatcher
 */
class Url extends \think\route\dispatch\Url
{
    /**
     * 执行路由调度
     * @access public
     * @return mixed
     */
    public function run(): Response
    {
        $option = $this->rule->getOption();
        if (isset($option['validate'])) {
            $this->autoValidate($option['validate']);
        }
        if ($this->rule instanceof RuleItem && $this->request->method() == 'OPTIONS' && $this->rule->isAutoOptions()) {
            $rules = $this->rule->getRouter()->getRule($this->rule->getRule());
            $allow = [];
            foreach ($rules as $item) {
                $allow[] = strtoupper($item->getMethod());
            }

            return Response::create('', 'html', 204)->header(['Allow' => implode(', ', $allow)]);
        }

        $data = $this->exec();
        return $this->autoResponse($data);
    }

    /**
     * 检查路由后置操作
     * @access protected
     * @return void
     */
    protected function doRouteAfter(): void
    {
        $option = $this->rule->getOption();

        // 添加中间件
        if (!empty($option['middleware'])) {
            $this->app->middleware->import($option['middleware'], 'route');
        }

        if (!empty($option['append'])) {
            $this->param = array_merge($this->param, $option['append']);
        }

        // 绑定模型数据
        if (!empty($option['model'])) {
            $this->createBindModel($option['model'], $this->param);
        }

        // 记录当前请求的路由规则
        $this->request->setRule($this->rule);

        // 记录路由变量
        $this->request->setRoute($this->param);
    }
}
